import typescript from '@rollup/plugin-typescript';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, resolve as pathResolve } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = pathResolve(__dirname, '..');

const pkg = JSON.parse(readFileSync(pathResolve(rootDir, 'package.json'), 'utf8'));

export default {
  input: pathResolve(rootDir, 'src/index.ts'),
  output: [
    {
      // CommonJS (用于 Node.js 环境)
      file: pathResolve(rootDir, 'dist/luckdog.cjs'),
      format: 'cjs',
      sourcemap: true,
      exports: 'named'
    },
    {
      // ES Module (用于现代打包工具如 webpack, rollup, vite 等)
      file: pathResolve(rootDir, 'dist/luckdog.esm.js'),
      format: 'es',
      sourcemap: true,
      exports: 'named'
    },
    {
      // UMD (通用模块定义，用于浏览器直接引用和 AMD)
      file: pathResolve(rootDir, 'dist/luckdog.umd.js'),
      format: 'umd',
      name: 'luckdog', // 全局变量名，用于直接在浏览器中使用
      sourcemap: true,
      exports: 'named'
    }
  ],
  plugins: [
    resolve(),
    commonjs(),
    typescript({
      tsconfig: pathResolve(rootDir, 'tsconfig.json'),
      declaration: true,
      declarationDir: pathResolve(rootDir, 'dist'),
    }),
    terser(),
  ],
  external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
}; 